﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace orderCreater
{
    public static class Files
    {
        // <summary> 
        /// 创建固定大小的临时文件 
        /// </summary> 
        /// <param name="fileName">文件名</param> 
        /// <param name="fileSize">文件大小</param> 
        /// <param name="overwrite">允许覆写：可以覆盖掉已经存在的文件</param> 
        public static void CreateFixedSizeFile(string fileName, long fileSize)
        {
            //验证参数 
            if (string.IsNullOrEmpty(fileName) || new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Contains(
                    fileName[fileName.Length - 1]))
                throw new ArgumentException("fileName");
            if (fileSize < 0) throw new ArgumentException("fileSize");
            //创建目录 
            string dir = Path.GetDirectoryName(fileName);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            //创建文件 
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Create);
                fs.SetLength(fileSize); //设置文件大小 
            }
            catch
            {
                if (fs != null)
                {
                    fs.Close();
                    File.Delete(fileName); //注意，若由fs.SetLength方法产生了异常，同样会执行删除命令，请慎用overwrite:true参数，或者修改删除文件代码。 
                }
                throw;
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }
        /// <summary>
        /// 读取大文件用,读取文件前面指定长度字节数
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="readByteLength">读取长度,单位字节</param>
        /// <returns></returns>
        public static string[] ReadBigFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                //FileInfo fileInfo = new FileInfo(filePath);
                //long readByteLength = fileInfo.Length;
                string[] strs = File.ReadAllLines(filePath);
                //File.WriteAllLines(@"d:\a.txt", str);
                return strs;
            }
            else return null;
            //string str = Encoding.Default.GetString(buffer) //如果需要转换成编码字符串的话
        }
        /// <summary>
        /// 普通文件读取方法
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ReaderFile(string path)
        {
            string fileData = string.Empty;
            ///读取文件的内容     
            StreamReader reader = new StreamReader(path, Encoding.Default);
            fileData = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            return fileData;
        }
    }
}
